package com.xiaodao.modules.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaodao.common.exception.ParamException;
import com.xiaodao.modules.system.entity.Dept;
import com.xiaodao.modules.system.mapper.DeptMapper;
import com.xiaodao.modules.system.service.IDeptService;
import com.xiaodao.modules.system.utils.LevelUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created by xiaodao
 * date: 2019/8/6
 */
@Service
public class DeptServiceImpl extends ServiceImpl<DeptMapper, Dept> implements IDeptService {


    public void insert(Dept entity) {
        if (checkExist(entity.getName(),entity.getParentId(),  entity.getId())) {
            throw new ParamException("相同名称的部门");

        }
        entity.setLevel(LevelUtil.calculateLevel(getLevel(entity.getParentId()), entity.getParentId()));
         baseMapper.insert(entity);
    }

    public boolean update(Dept entity) {
        if (checkExist(entity.getParentId(), entity.getName(), entity.getId())) {
            throw new ParamException("相同名称的部门");
        }
        Dept before = baseMapper.selectById(entity.getId());
        entity.setLevel(LevelUtil.calculateLevel(getLevel(entity.getParentId()), entity.getParentId()));
        updateWithChild(before, entity);
        return updateById(entity);
    }
    @Transactional
    public void updateWithChild(Dept before, Dept after) {

        String nextLevel = before.getLevel();
        String oldLevel = after.getLevel();
        //需要更新子部门
        if(!nextLevel.equals(oldLevel)){
            QueryWrapper<Dept> deptQueryWrapper = new QueryWrapper<Dept>().like("level", before.getLevel())
                    .or().likeRight("level", ".");
            List<Dept> depts = baseMapper.selectList(deptQueryWrapper);
            if(CollectionUtils.isNotEmpty(depts)){
                for (Dept dept : depts) {
                    String level = dept.getLevel();
                    if(level.indexOf(oldLevel) == 0){
                            level = oldLevel +level.substring(oldLevel.length());
                            dept.setLevel(level);
                    }

                }
            }
            baseMapper.batchUpdateLevel(depts);
        }
        baseMapper.updateById(after);


    }

    private boolean checkExist(String deptName,String parentId,  String deptId) {
        return  baseMapper.countByNameAndParentId(deptName, parentId,  deptId) >0 ;

    }

    private String getLevel(String deptId) {
        Dept dept = baseMapper.selectById(deptId);
        if (dept == null) {
            return null;
        } else {
            return dept.getLevel();
        }
    }
}
